package com.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mapper.CVideoMapper;
import com.pojo.dto.Message;
import com.pojo.entity.CVideo;
import com.pojo.vo.CVideoVo;
import com.service.CVideoService;
import com.util.ConverVideoUtils;
import com.util.PojoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service("/CVideoService")
public class CVideoServiceImpl implements CVideoService {
    @Value("${prop.upload-folder}")
    /*@Value("${prop.upload-picture}")*/
    private String UPLOAD_FOLDER;
    @Autowired
    CVideoMapper cVideoMapper;

    /**
     * 视频上传
     * 只能上传mp4 avi mov格式的视频,保存路径和最大上传文件大小在application.yml中设置,
     * 默认上传路径为files,默认上传文件大小最大为20MB
     *
     * @param cVideoVo
     * @return
     */
    @Override
    public Message<CVideoVo> add(CVideoVo cVideoVo) {
        MultipartFile file = cVideoVo.getFile();
        if (Objects.isNull(file) || file.isEmpty()) {
            return Message.errorMessage("1001", "文件为空，请重新上传");
        }
        String videoName = file.getOriginalFilename();//获取文件名称
        String toLowerCase = videoName.substring(videoName.lastIndexOf(".") + 1, videoName.length()).toLowerCase();//获取上传文件的文件类型
        //获取项目在此电脑上的真实路径
        String fileTrue = System.getProperty("user.dir");
        fileTrue += "\\"+"happy\\src\\main\\resources\\static\\files\\video\\";
        String img[] = {"mp4", "avi", "mov"};
        //判断文件类型,"mp4""avi"为Android手机拍摄常用视频格式,"mov"为Apple手机拍摄视频常用格式
        for (int i = 0; i < img.length; i++) {
            if ((img[i].equals(toLowerCase))) {
                try {
                    byte[] bytes = file.getBytes();
                    Path path = Paths.get(fileTrue + file.getOriginalFilename());
                    //如果没有files文件夹，则创建
                    if (!Files.isWritable(path)) {
                        Files.createDirectories(Paths.get(fileTrue));
                    }
                    //短视频文件写入指定路径
                    Files.write(path, bytes);
                    String pathVideo = String.valueOf(path);//短视频的存储路径

                    //帧截取的实现
                    ConverVideoUtils cv = new ConverVideoUtils(pathVideo);
                    String videoTruth = pathVideo.substring(pathVideo.lastIndexOf("\\") + 1);//获取video的名
                    boolean b = cv.processImg(pathVideo);

                    String picTruth=videoTruth.substring(0,videoTruth.lastIndexOf(".")+1).concat("jpg");
                    cVideoVo.setVideoPath("http://wgy.vaiwan.com/files/video/" + videoTruth);
                    cVideoVo.setPicturePath("http://wgy.vaiwan.com/files/pic/"+picTruth);
                    cVideoVo.setPublishTime(new Date());
                    cVideoVo.setPraise((long) 0);
                    cVideoVo.setComment((long) 0);
                    int insert = cVideoMapper.insert(PojoUtil.copyObject(cVideoVo, CVideo.class));
                    CVideoVo video = new CVideoVo();
                    video.setPicturePath(cVideoVo.getPicturePath());
                    video.setVideoPath(cVideoVo.getVideoPath());
                    video.setVideoName(cVideoVo.getVideoName());
                    video.setId(cVideoVo.getId());
                    video.setUserNum(cVideoVo.getUserNum());

                    if (insert == 0) {
                        return Message.errorMessage("1001", "文件上传失败");
                    } else {
                        return Message.successMessage(1L, video);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                    return Message.errorMessage("1001", "后端异常...");

                }

            }
        }
        return Message.errorMessage("1001", "上传文件格式不符合，请重新上传...");
    }

    /**
     * 视频批量查询
     * 将数据库中的所有视频信息查询出,并返回到前台
     *
     * @return
     */
    @Override
    public Message<List<CVideoVo>> videoList() {
        List<CVideo> cVideos = cVideoMapper.selectList(null);
        if (cVideos.size() == 0) {
            return Message.errorMessage("1001", "数据库为空,无视频播放");
        } else {
            return Message.successMessage(1L, PojoUtil.copyList(cVideos, CVideoVo.class));
        }
    }

    /**
     * 带参数的视频批量查询
     *
     * @param cVideoVo
     * @return
     */
    @Override
    public Message<List<CVideoVo>> videoListByUser(CVideoVo cVideoVo) {
        CVideo cVideo = PojoUtil.copyObject(cVideoVo, CVideo.class);
        QueryWrapper<CVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_num", cVideo.getUserNum());
        List<CVideo> cVideos = cVideoMapper.selectList(wrapper);
        if (cVideos.size() == 0) {
            return Message.errorMessage("1001", "数据库为空,无视频播放");
        } else {
            return Message.successMessage(1L, PojoUtil.copyList(cVideos, CVideoVo.class));
        }
    }

    @Override
    public Message<CVideoVo> selectOneVideo(CVideoVo cVideoVo) {
        CVideo cVideo = cVideoMapper.selectById(cVideoVo.getId());
        return Message.successMessage(1L, PojoUtil.copyObject(cVideo, CVideoVo.class));
    }

    /**
     * 修改视频的点赞数、评论数
     * 接收前台发送来的CVideoVo对象,将接收到的对象中的点赞数和评论数在数据库进行更新
     *
     * @param cVideoVo
     * @return
     */
    @Override
    public Message<CVideoVo> updateVideo(CVideoVo cVideoVo) {
        CVideo cVideo = PojoUtil.copyObject(cVideoVo, CVideo.class);
        int update = cVideoMapper.updateById(cVideo);
        if (update == 0) {
            return Message.errorMessage("1001", "评论/点赞更新失败");
        } else {
            return Message.successMessage(1L, cVideoVo);
        }

    }

    /**
     * 单个视频删除
     *
     * @param cVideoVo
     * @return
     */
    @Override
    public Message<String> deleteVideo(CVideoVo cVideoVo) {
        Long id = cVideoVo.getId();
        int delete = cVideoMapper.deleteById(id);
        if (delete == 0) {
            return Message.errorMessage("1001", "视频删除失败");
        } else {
            return Message.successMessage(1L, "删除成功");
        }
    }

    /**
     * 视频批量删除
     *
     * @param videos
     * @return
     */
    @Override
    public Message<String> deleteVideoList(List<CVideoVo> videos) {

        for (int i = 0; i < videos.size(); i++) {
            deleteVideo(videos.get(i));
        }
        return Message.successMessage(1L, "已经全部删除成功");
    }
}
